import React, { useState, useEffect, useRef } from 'react';
import '../index.css';
import contentsIcon from '@/assets/images/contents-icon.png';
import { ImageElement } from '@/core/element/image';
import UploadImg from './uploadImg';
import { delDir, delFile, getloadDirList, getloadFileList, saveDirApi } from '@/api';
import { Modal, Input, message, Checkbox, Button } from 'antd';
import { set } from 'lodash';

type TreeNode = {
    id: string;
    title: string;
    type: 'folder' | 'image';
    children?: TreeNode[];
    url?: string; // for image
};
const Photolbrary: React.FC = () => {
    const [activeNode, setActiveNode] = useState<TreeNode>({ id: '0', title: '根目录', type: 'folder' });
    const [breadcrumb, setBreadcrumb] = useState<TreeNode[]>([]);
    const [treeData, setTreeData] = useState<TreeNode[]>([]);
    const [nodeMap, setNodeMap] = useState<Map<string, any>>(new Map());
    const [galleryImages, setGalleryImages] = useState<any[]>([]);
    const [imagelist, setImagelist] = useState<string[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [newFolderName, setNewFolderName] = useState('');
    const [selectedImages, setselectedImages] = useState<any[]>([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalOpen1, setIsModalOpen1] = useState(false);
    // const [catalogIitem, setCatalogIitem] = useState<any>(null);
     const catalogIitem = useRef<any>('');
    useEffect(() => {
        getData();
    }, []);

    const getData = async () => {
        const { code, data } = await getloadDirList({})
        let arr: any = data.map((v: any) => {
            return {
                ...v,
                pid: v.pid ? v.pid : 0
            }
        })
        arr.unshift({ title: '全部', id: 0 })
        const tree = handleTree(arr, 'id', 'pid');
        setTreeData(tree);
        console.log('tree', tree);
        if (tree.length > 0) {
            handleNodeClick(tree[0]);
        }
    }

    const handleTree = (data: any, id: any, parentId: any, children?: any) => {
        let config = {
            id: id || 'id',
            parentId: parentId || 'parentId',
            childrenList: children || 'children'
        }
        var childrenListMap: any = {}
        var tree = []
        for (let d of data) {
            let id = d[config.id]
            childrenListMap[id] = d
            if (!d[config.childrenList]) {
                d[config.childrenList] = []
            }
        }
        for (let d of data) {
            let parentId = d[config.parentId]
            let parentObj = childrenListMap[parentId]
            if (!parentObj) {
                tree.push(d)
            } else {
                parentObj[config.childrenList].push(d)
            }
        }
        return tree
    }

    // 处理节点点击事件
    const handleNodeClick = (node: any) => {
        setActiveNode(node);
        console.log('activeNode (next):', node); // Use node directly
        getimglist(node); // Pass node as argument
        buildBreadcrumb(node)

    }
    // 构建面包屑路径
    const buildBreadcrumb = (node: any) => {
        // 初始化 nodeMap
        const map = new Map<string, any>();
        const traverse = (nodes: any[]) => {
            nodes.forEach((n) => {
                map.set(n.id, n);
                if (n.children && n.children.length > 0) {
                    traverse(n.children);
                }
            });
        };
        traverse(treeData);

        setNodeMap(map);

        const path = [];
        let currentId: string | null = node.id;
        // 使用迭代回溯父节点
        while (currentId && map.has(currentId)) {
            const currentNode = map.get(currentId);
            path.unshift(currentNode); // 添加到路径开头
            // 终止条件：到达根节点
            if (!currentNode.pid || currentNode.pid === '0') break;
            currentId = currentNode.pid;
        }
        setBreadcrumb(path);

    }
    const selectBreadcrumball = () => {
        handleNodeClick(treeData[0])
    }
    const getimglist = async (node?: any) => {
        const dirId = node ? node.id : activeNode.id;
        const { code, data } = await getloadFileList({ dirid: dirId });
        if (code === 200) {
            console.log('图片列表', data);
            data.forEach((item: any) => {
                item.check = false
                item.storagepath = item.storagepath.replace('http://61.140.17.226:8089', '') //本地调试开启
            })
            setGalleryImages(data);
            setImagelist(data.map((v: any) => v.storagepath));
        }
    }
    const DeleteNode = async () => {
        const { code } = await delDir({ id: catalogIitem.current.id })
        if (code == 200) {
            // console.log('删除成功')
            message.success('删除成功')
            let arr = activeNode.children?.filter((v: any) => v.id != catalogIitem.current.id) || []
            setActiveNode({...activeNode, children:arr})

            setIsModalOpen1(false);
            // getData()
        } else {
            console.log('删除失败')
            message.error('删除失败')
            setIsModalOpen1(false);
        }
    }
    const handleAddFolder = async () => {
        if (!newFolderName.trim()) {
            message.error('请输入目录名称');
            return;
        }
        const { code, data } = await saveDirApi({
            title: newFolderName,
            indexNum: 0,
            pid: activeNode.id ? activeNode.id : null
        })
        if (code == 200) {
            message.success('新增目录成功')
            if (activeNode && activeNode.id) {
                getDatatrow(activeNode)
            } else {
                getData()
            }
        } else {
            message.error('新增目录失败')
        }
        setNewFolderName('');
        setModalVisible(false);
    };
    const getDatatrow = async (item: any) => {
        const { code, data } = await getloadDirList({ pid: item.id })
        item.children = data
        setActiveNode({ ...item })
    }
    const handleCheckboxChange = (v: any) => {
        const selectedImages = galleryImages.filter((v: any) => v.check)
        console.log('selectedImages', selectedImages);
        setselectedImages(selectedImages)
    }

    const showModal = () => {
        if (selectedImages.length == 0) {
            message.error('请选择要删除的图片')
            return
        }
        setIsModalOpen(true);
    };
    const downloadList = () => {
        if (selectedImages.length == 0) {
            message.error('请选择要下载的图片')
            return
        }
        selectedImages.forEach((item: any) => {
            download(item);
        })
    }

    const download = (item: any) => {
        const a = document.createElement('a')
        a.href = item.storagepath
        a.download = item.filename || 'downloaded-file' // 设置下载的文件名
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
    }
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const DeleteImgList = async () => {
        const deletePromises = selectedImages.map((item: any) => delFile({ id: item.id }))
        try {
            const results = await Promise.allSettled(deletePromises)
            let successCount = 0
            let failCount = 0
            results.forEach((result, index) => {
                if (result.status === 'fulfilled' && result.value.code === 200) {
                    successCount++
                } else {
                    failCount++
                }
            })
            if (successCount > 0) {
                setselectedImages([])
                await getimglist() // 重新获取列表
                message.success(`成功删除 ${successCount} 张图片`)
                setIsModalOpen(false);
            }
            if (failCount > 0) {
                message.warning(`${failCount} 张图片删除失败`)
                setIsModalOpen(false);
            }
        } catch (error) {
            setIsModalOpen(false);
            message.error('批量删除过程中出现错误')
        }
    }

    return (
        <div className='warp'>
            <div className='header'>
                <nav className="breadcrumb">
                    <span onClick={() => selectBreadcrumball()}>
                        全部 {breadcrumb.length > 0 && <span> / </span>}
                    </span>
                    {breadcrumb.map((node, idx) => (
                        <span key={node.id} onClick={() => handleNodeClick(node)} style={{ cursor: 'pointer' }}>
                            {node.title}
                            {idx < breadcrumb.length - 1 && <span> / </span>}
                        </span>
                    ))}
                </nav>
                <div className="addbPhotolbrary" title="新增目录" onClick={() => setModalVisible(true)}>
                    <span style={{ cursor: 'pointer', fontSize: '20px' }}>＋</span>
                </div>
            </div>
            <div
                className="Photolbrary"
            >
                {/* */}
                {activeNode.children && activeNode.children.map((child: TreeNode) => (
                    <div className="Photo-item" key={child.id} onClick={() => handleNodeClick(child)}>
                        <div className='iconimg'>
                            <img
                                src={contentsIcon}
                                alt="contents icon"
                            />
                        </div>
                        <div className="name">{child.title}</div>
                        <div
                            className="del"
                            onClick={(e) => {
                                e.stopPropagation(); // 禁止事件穿透
                                catalogIitem.current = child;
                                setIsModalOpen1(true);
                            }}
                        >
                            <svg
                                width="20"
                                height="20"
                                viewBox="0 0 20 20"
                                fill="none"
                                xmlns="http://www.w3.org/2000/svg"
                                style={{ cursor: 'pointer' }}
                            >
                                <rect width="20" height="20" rx="10" fill="#F5F5F5" />
                                <path d="M7 7L13 13M13 7L7 13" stroke="#888" strokeWidth="2" strokeLinecap="round" />
                            </svg>
                        </div>
                    </div>
                ))}
                {galleryImages.map((img: any) => (
                    <div className="Photo-item" key={img.id}>
                        <div
                            className="iconimg"
                            draggable
                            onDragStart={e => {
                                e.dataTransfer.setData('imageSrc', img.storagepath);
                                e.dataTransfer.setData('imageFilename', img.filename || '');
                            }}
                            onDragEnd={e => {
                                // 拖拽结束时的处理逻辑
                                const image = new ImageElement();
                                image.addImage(img.storagepath);
                            }}
                            onClick={(e) => {
                                e.stopPropagation(); // 禁止事件穿透
                                const image = new ImageElement();
                                image.addImage(img.storagepath);
                            }}
                        >
                            <img src={img.storagepath} alt={img.filename || ''} />
                        </div>
                        <div className="name">{img.filename || '图片'}</div>
                        <Checkbox
                            className="imgcheckbox"
                            value={img.check}
                            onChange={e => {
                                img.check = e.target.checked;
                                handleCheckboxChange(img);
                            }}

                        ></Checkbox>
                    </div>
                ))}
                {
                    activeNode.id != '0' ? (
                        <div className="Photo-item-add" >
                            <UploadImg dirid={activeNode.id} updata={getimglist} onUpload={
                                (file: File) => {
                                    console.log('Selected file:', file);
                                }} ></UploadImg>
                            {/* <uploadImg :dirid="activeNode.id" @updata="getimglist"></uploadImg> */}
                        </div>
                    ) : ''
                }

            </div>
            <div className="foot-btn">
                <Button type="primary" danger onClick={showModal}>
                    删除
                </Button>
                <button onClick={downloadList}>下载</button>
            </div>
            <Modal
                title="新增目录"
                open={modalVisible}
                onOk={handleAddFolder}
                onCancel={() => setModalVisible(false)}
                okText="确定"
                cancelText="取消"
            >
                <Input
                    placeholder="请输入目录名称"
                    value={newFolderName}
                    onChange={e => setNewFolderName(e.target.value)}
                    onPressEnter={handleAddFolder}
                />
            </Modal>
            <Modal
                title="温馨提示"
                closable={{ 'aria-label': 'Custom Close Button' }}
                open={isModalOpen}
                onOk={DeleteImgList}
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
            >
                <p>是否确认删除这些图片</p>
            </Modal>
            <Modal
                title="温馨提示"
                closable={{ 'aria-label': 'Custom Close Button' }}
                open={isModalOpen1}
                onOk={DeleteNode}
                onCancel={() => setIsModalOpen1(false)}
                okText="确定"
                cancelText="取消"
            >
                <p>是否确认删除该目录</p>
            </Modal>
        </div>
    );
}


export default Photolbrary;
